from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.hashers import make_password, check_password

# Create your views here.


def account_login(request):
    """
    登录视图
    """
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
            request.session["bar"]=0
            if request.GET.get('next'):
                return redirect(request.GET.get('next'))
            else:
                return redirect('/')
        else:
            return render(request, 'login.html', {"error": '用户名密码错误'})
    else:
        return render(request, 'login.html')


def account_logout(request):
    """
    退出视图
    :param request:
    :return:
    """
    logout(request)
    return redirect('/login/')

@login_required(login_url='/login/')
def userinfo(request):
    if request.method == 'POST':
       old_password = request.POST.get('old_password')
       new_password = request.POST.get('password')
       re_new_password = request.POST.get('re_password')
       email = request.POST.get('email')
       user = User.objects.get(username=request.user)
       if check_password(old_password,user.password):
          if new_password:
             if new_password == re_new_password:
                user.set_password(new_password)
             else:
                messages.error(request,"两次输入密码不一致，请重新输入")
                return HttpResponseRedirect('/userinfo')
          else:
             messages.error(request,"密码不能为空，请重新输入")
             return HttpResponseRedirect('/userinfo')
       else:
           messages.error(request,"旧密码输入错误，请重新输入")
           return HttpResponseRedirect('/userinfo')
       user.email = email
       user.save()
       user = authenticate(username=request.user, password=new_password)
       login(request, user)
       return HttpResponseRedirect('/userinfo')
    else:
       return render(request, 'userinfo.html')
